import subprocess
import sys
from app.core.config import exec_log as log


def run_cmd(cmd, file_output=None):
    """
    执行命令并发送初始信息给mq
    :param cmd: 执行的备份命令
    :param file_output: 日志输出
    :return:
    """
    log.debug(cmd)
    if file_output is None:
        stdout = subprocess.PIPE
        stderr = subprocess.STDOUT
    else:
        stdout = file_output
        stderr = file_output
    p = subprocess.Popen(cmd,
                         shell=True,
                         stdout=sys.stdout,
                         stderr=stderr)
    pid = p.pid
    # try:
    #     information.set_pid_info(pid=pid)
    #     information.backup_startup_publish()
    # except AttributeError as e:
    #     pass
    # result = p.stdout.read()
    return_code = p.wait()
    try:
        p.stdout.flush()
        stdout_str = p.stdout.readline()
    except Exception as e:
        stdout_str = None
    try:
        stderr_str = p.stderr.readline()
    except Exception as e:
        stderr_str = None

    return return_code, stdout_str, stderr_str
